﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BookStore.Models;
using System.Data;
namespace BookStore.Controllers
{
    [HandleError]
    public class CartController : Controller
    {
        public ActionResult Buy()
        {
            BookModel tbBook = new BookModel();

            DataTable result = new DataTable();

            if (Request.RequestType == "POST")
            {
                string[][] check = (string[][])this.Session["buy"];
                if (check != null)
                {
                    for (int i = 0; i < check.Length; i++)
                    {
                        if (check.Length > 0 && check[i][0] != null && check[i][0] != "")
                        {
                            string id = check[i][0];
                            string remove = Request.Form["book_"+id];
                            string[] limit = new string[5];
                            try
                            {
                                limit = tbBook.getBookPricebyID(Convert.ToInt32(id));
                            }
                            catch (SystemException err)
                            {
                            }
                            finally
                            {
                                if (remove == null)
                                {
                                    string sl = Request.Form["sl_" + id];
                                    if (sl != null && sl != "" && sl != "0" && Convert.ToInt32(sl) <= Convert.ToInt32(limit[3]))
                                    {
                                        string price = Request.Form["price_" + id];
                                        long total = 0;
                                        total = Convert.ToInt32(sl) * Convert.ToInt64(price);
                                        check[i][1] = total.ToString();
                                        check[i][2] = sl;
                                    }
                                    if (Convert.ToInt32(sl) > Convert.ToInt32(limit[3]))
                                    {
                                        ViewData["error"] = "Số lượng sách không đủ !";
                                    }
                                }
                                else if(remove == "on")
                                {
                                    check = Array.FindAll(check, val => val != check[i]).ToArray();
                                    i--;
                                }
                            }
                        }

                    }
                    this.Session["buy"] = check;
                }
            }

            string[][] buy = (string[][])this.Session["buy"];
            if (buy != null)
            {
                string[][] books = new string[buy.Length][];
                long total = 0;
                for (int i = 0; i < buy.Length; i++)
                {
                    if (buy[i].Length > 0 && buy[i][0] != null && buy[i][0] != "")
                    {
                        string[] temp = new string[15];
                        try
                        {
                            temp = tbBook.getDetailBookbyID(Convert.ToInt32(buy[i][0]));
                        }
                        catch (SystemException err)
                        {
                        }
                        finally
                        {
                            books[i] = new string[15];
                            temp.CopyTo(books[i], 0);
                            books[i][13] = buy[i][2];
                            books[i][14] = buy[i][1];
                            total = total + Convert.ToInt64(buy[i][1]);
                        }
                    }
                }
                ViewData["books"] = books;
                ViewData["total"] = total.ToString();
            }
            else
            {
                ViewData["books"] = null;
            }

            
            return View();
        }

        public ActionResult Rent()
        {
            BookModel tbBook = new BookModel();

            DataTable result = new DataTable();

            if (Request.RequestType == "POST")
            {
                string[][] check = (string[][])this.Session["rent"];
                if (check != null)
                {
                    for (int i = 0; i < check.Length; i++)
                    {
                        if (check.Length > 0 && check[i][0] != null && check[i][0] != "")
                        {
                            string id = check[i][0];
                            string remove = Request.Form["book_" + id];
                            string[] limit = new string[5];
                            try
                            {
                                limit = tbBook.getBookPricebyID(Convert.ToInt32(id));
                            }
                            catch (SystemException err)
                            {
                            }
                            finally
                            {
                                if (remove == null)
                                {
                                    string sl = Request.Form["sl_" + id];
                                    string sn = Request.Form["sn_" + id];
                                    if (sl != null && sl != "" && sn != null && sn != "" && sl != "0" && sn != "0" && Convert.ToInt32(sl) <= Convert.ToInt32(limit[4]))
                                    {
                                        string price = Request.Form["price_" + id];
                                        long total = 0;
                                        total = Convert.ToInt32(sl) * Convert.ToInt64(price) * Convert.ToInt32(sn);
                                        check[i][1] = total.ToString();
                                        check[i][2] = sl;
                                        check[i][3] = sn;
                                    }
                                    if (Convert.ToInt32(sl) > Convert.ToInt32(limit[4]))
                                    {
                                        ViewData["error"] = "Số lượng sách không đủ !";
                                    }
                                }
                                else if (remove == "on")
                                {
                                    check = Array.FindAll(check, val => val != check[i]).ToArray();
                                    i--;
                                }
                            }
                        }

                    }
                    this.Session["rent"] = check;
                }
            }

            string[][] rent = (string[][])this.Session["rent"];
            if (rent != null)
            {
                string[][] books = new string[rent.Length][];
                long total = 0;
                for (int i = 0; i < rent.Length; i++)
                {
                    if (rent[i].Length > 0 && rent[i][0] != null && rent[i][0] != "")
                    {
                        string[] temp = new string[15];
                        try
                        {
                            temp = tbBook.getDetailBookbyID(Convert.ToInt32(rent[i][0]));
                        }
                        catch (SystemException err)
                        {
                        }
                        finally
                        {
                            books[i] = new string[16];
                            temp.CopyTo(books[i], 0);
                            books[i][13] = rent[i][2];
                            books[i][14] = rent[i][1];
                            books[i][15] = rent[i][3];
                            total = total + Convert.ToInt64(rent[i][1]);
                        }
                    }
                }
                ViewData["books"] = books;
                ViewData["total"] = total.ToString();
            }
            else
            {
                ViewData["books"] = null;
            }


            return View();
        }

        public ActionResult JsonAddCartBuy()
        {
            if (this.Request.QueryString["id"] != null)
            {
                int book_id = Convert.ToInt32(this.Request.QueryString["id"]);
                BookModel tbBook = new BookModel();
                try
                {
                    string[] detail = new string[5];
                    detail = tbBook.getBookPricebyID(book_id);
                    if (detail[3] == "0" || detail[3] == null)
                    {
                        return Content("-2");
                    }
                    string[][] check = (string[][])this.Session["buy"];
                    if (check == null || check.Length == 0)
                    {
                        string[][] test = new string[1][];
                        test[0] = new string[3];
                        test[0][0] = detail[0];
                        test[0][1] = detail[1];
                        test[0][2] = "1";
                        this.Session["buy"] = test;
                    }
                    else
                    {
                        Boolean ch = false;
                        int i = 0;
                        foreach (string[] temp in check)
                        {

                            if (temp[0] == detail[0])
                            {
                                if(Convert.ToInt64(temp[2]) + 1 > Convert.ToInt32(detail[3]))
                                    return Content("-3");
                                check[i][1] = (Convert.ToInt64(temp[1]) + Convert.ToInt64(detail[1])).ToString();
                                check[i][2] = (Convert.ToInt32(temp[2]) + 1).ToString();
                                ch = true;
                                break;
                            }
                            i++;
                        }
                        if (ch == true)
                        {
                            this.Session["buy"] = check;
                        }
                        else
                        {
                            string[][] temp2 = new string[check.Length+1][];
                            check.CopyTo(temp2, 0);
                            string[] test = new string[3];
                            test[0] = detail[0];
                            test[1] = detail[1];
                            test[2] = "1";
                            temp2[check.Length] = test;
                            this.Session["buy"] = temp2;
                        }
                    }
                    string[][] buy = (string[][])this.Session["buy"];
                    string[] temp3 = new string[2];
                    long money = 0;
                    int total_book = 0;
                    
                    for (int j = 0; j < buy.Length; j++)
                    {
                        money = money + Convert.ToInt64(buy[j][1]);
                        total_book += Convert.ToInt32(buy[j][2]);
                    }
                    temp3[0] = total_book.ToString();
                    temp3[1] = money.ToString();

                    string output = "";
                    output += "<div style='clear:both;'></div><div class='home_cart_content'>Mua : "+ temp3[0] + " x cuốn | <span class='red'>" + temp3[1] + " VNĐ</span></div><a href='/cart/buy' class='view_cart'>Giỏ hàng</a>";
                    return Content(output);
                }
                catch (SystemException err)
                {
                    return Content("-1");
                }
            }
            return Content("-1");
        }

        public ActionResult JsonAddCartRent()
        {
            if (this.Request.QueryString["id"] != null)
            {
                int book_id = Convert.ToInt32(this.Request.QueryString["id"]);
                BookModel tbBook = new BookModel();
                try
                {
                    string[] detail = new string[5];
                    detail = tbBook.getBookPricebyID(book_id);
                    if (detail[4] == "0" || detail[4] == null)
                    {
                        return Content("-2");
                    }
                    string[][] check = (string[][])this.Session["rent"];
                    if (check == null || check.Length == 0)
                    {
                        string[][] test = new string[1][];
                        test[0] = new string[4];
                        test[0][0] = detail[0];
                        test[0][1] = detail[2];
                        test[0][2] = "1";
                        test[0][3] = "1";
                        this.Session["rent"] = test;
                    }
                    else
                    {
                        Boolean ch = false;
                        int i = 0;
                        foreach (string[] temp in check)
                        {

                            if (temp[0] == detail[0])
                            {
                                if (Convert.ToInt64(temp[2]) + 1 > Convert.ToInt32(detail[4]))
                                    return Content("-3");
                                check[i][1] = (Convert.ToInt64(temp[1]) + Convert.ToInt64(detail[2]) * Convert.ToInt64(temp[3])).ToString();
                                check[i][2] = (Convert.ToInt32(temp[2]) + 1).ToString();
                                ch = true;
                                break;
                            }
                            i++;
                        }
                        if (ch == true)
                        {
                            this.Session["rent"] = check;
                        }
                        else
                        {
                            string[][] temp2 = new string[check.Length + 1][];
                            check.CopyTo(temp2, 0);
                            string[] test = new string[4];
                            test[0] = detail[0];
                            test[1] = detail[2];
                            test[2] = "1";
                            test[3] = "1";
                            temp2[check.Length] = test;
                            this.Session["rent"] = temp2;
                        }
                    }
                    string[][] rent = (string[][])this.Session["rent"];
                    string[] temp3 = new string[2];
                    long money = 0;
                    int total_book = 0;

                    for (int j = 0; j < rent.Length; j++)
                    {
                        money = money + Convert.ToInt64(rent[j][1]);
                        total_book += Convert.ToInt32(rent[j][2]);
                    }
                    temp3[0] = total_book.ToString();
                    temp3[1] = money.ToString();

                    string output = "";
                    output += "<div style='clear:both;'></div><div class='home_cart_content'>Thuê : " + temp3[0] + " x cuốn | <span class='red'>" + temp3[1] + " VNĐ</span></div><a href='/cart/rent' class='view_cart'>Giỏ hàng</a>";
                    return Content(output);
                }
                catch (SystemException err)
                {
                    return Content("-1");
                }
            }
            return Content("-1");
        }

        public ActionResult HistoryOrder()
        {
            BillModel bill = new BillModel();
            if (Session["Session_User"] != null)
            {
                string[][] result;
                result = bill.getBillRentByUserID(Convert.ToInt32(Session["Session_User"].ToString()));
                ViewData["result"] = result;
            }
            else Response.Redirect("/home/index");
            
            return View();
        }
        public ActionResult DetailOrderBill()
        {
            BillModel bill = new BillModel();
            string[][] result=null;
            try
            {
                if (Session["Session_User"] != null)
                {
                    if (this.Request.QueryString["type"] == null || this.Request.QueryString["id"] == null || Utils.IsNumber(this.Request.QueryString["id"]) != true)
                    {
                        Response.Redirect("/home/index");
                    }
                    else
                    {

                        if (this.Request.QueryString["type"] == "Buy")
                        {

                            result = bill.getBillDetailUserID(Convert.ToInt32(this.Request.QueryString["id"]));
                            ViewData["result"] = result;
                            ViewData["type"] = this.Request.QueryString["type"];
                            ViewData["total_shipping"] = bill.getShippingCostByBillID(this.Request.QueryString["type"], Convert.ToInt32(this.Request.QueryString["id"]));
                        }
                        else
                        {

                            result = bill.getBillRentDetailUserID(Convert.ToInt32(this.Request.QueryString["id"]));
                            ViewData["result"] = result;
                            ViewData["deposit"] = bill.getDepositByBillRentID(Convert.ToInt32(this.Request.QueryString["id"]));
                            ViewData["type"] = this.Request.QueryString["type"];
                            ViewData["total_shipping"] = bill.getShippingCostByBillID(this.Request.QueryString["type"], Convert.ToInt32(this.Request.QueryString["id"]));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }
        
    }
}
